package com.sq.orders.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.util.BeanUtil;
import com.sq.orders.dao.OrdersDao;
import com.sq.orders.entity.Orders;
import com.sq.orders.entity.User;
import com.sq.orders.service.OrdersService;
import com.sq.orders.vo.R;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * (Orders)表服务实现类
 *
 * @author 全哥哥
 * @since 2025-05-13 10:40:03
 */
@Service("ordersService")
public class OrdersServiceImpl extends ServiceImpl<OrdersDao, Orders> implements OrdersService {

    @Autowired
    private RestTemplate restTemplate;

    @Override
    public List myList() {
        List<Orders> list = list();
        List<Orders> ordersList = list.stream().map(orders -> {
            Integer userId = orders.getUserId();
            R r = restTemplate.getForObject("http://localhost:9001/user/" + userId, R.class);
            Object data = r.getData();
            User user = new User();
            try {
                BeanUtils.populate(user, (Map<String, ? extends Object>) data);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            } catch (InvocationTargetException e) {
                throw new RuntimeException(e);
            }
            orders.setUser(user);
            return orders;
        }).collect(Collectors.toList());
        return ordersList;
    }

    @Override
    public Orders myGetById(Serializable id) {
        Orders orders = getById(id);
        Integer userId = orders.getUserId();
        R r = restTemplate.getForObject("http://localhost:9001/user/" + userId, R.class);
        Object data = r.getData();
        User user = new User();
        try {
            BeanUtils.populate(user,(Map<String, ? extends Object>) data);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }
        orders.setUser(user);
        return orders;
    }
}

